package com.gzlz.budejie.activity;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.json.JSONArray;
import org.json.JSONException;

import com.google.gson.Gson;
import com.gzlz.budejie.R;
import com.gzlz.budejie.activity.SubscribeActivity.ViewHolder;
import com.gzlz.budejie.bean.SearchBean;
import com.gzlz.budejie.bean.SubscribeBean;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class SubscribeSearchActivity extends Activity implements TextWatcher,
		OnClickListener {

	@ViewInject(R.id.search_keywords_text)
	private EditText search_keywords_text;
	@ViewInject(R.id.cancel_btn)
	private TextView cancel_btn;
	@ViewInject(R.id.fl_bg)
	private TextView fl_bg;
	@ViewInject(R.id.listview_sub)
	private ListView listview;
	public String url="";
	private Handler handler;
	protected String textSearch;
	private ArrayList data;
	private List<SearchBean> searchData ;
	private SearchBean searchBean;
	private BitmapUtils bitmapUtils;
	private SearchAdapter searchAdapter= new SearchAdapter();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_subscribe_search);
		initView();
		bitmapUtils = new BitmapUtils(SubscribeSearchActivity.this);
		bitmapUtils.configDefaultBitmapConfig(Config.ARGB_4444);
		
	}

	private void initView() {
		ViewUtils.inject(this);
		search_keywords_text.addTextChangedListener(this);
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				if (msg.what==0) {
					
					if (msg.obj.toString().equals("")) {
						fl_bg.setVisibility(View.GONE);
						listview.setVisibility(View.GONE);
						return;
					}
					textSearch=msg.obj.toString();
					
					Log.e("TAG","Handler"+ textSearch);
					fl_bg.setVisibility(View.VISIBLE);
					listview.setVisibility(View.VISIBLE);
					fl_bg.setText("点击搜索：“"+textSearch+"”");
					url = "https://api.budejie.com/api/api_open.php?c=topic&a=tag_search&kw="
							+textSearch+"&limit=20";
					
				} 
				
			}
		};
		fl_bg.setOnClickListener(this);
		cancel_btn.setOnClickListener(this);
		
		
		
	}
	/**
	 * 网络请求
	 */
	private void getDataFromNet() {
		HttpUtils httpUtils = new HttpUtils();
		Log.e("TAG", url);
		httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				// 解析和处理数据
				processData(responseInfo.result);
				Log.e("TAG", "网络连接成功了：" + responseInfo.result);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e("TAG", "网络连接失败：" + msg);
			}
		});

	}

	protected void processData(String result) {
		
		try {
			JSONArray jsonArray = new JSONArray(result);
			for (int i = 0; i < jsonArray.length(); i++) {
				Gson gson = new Gson();
				String json = jsonArray.get(i).toString();
				SearchBean searchBean = gson.fromJson(json, SearchBean.class);
				//searchData.add(searchBean);
				
				searchData.add(searchBean);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//Log.e("TAG", "解析成功" + searchData.get(0).theme_name);
		
		listview.setAdapter(searchAdapter);
	}
	class SearchAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return searchData.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView ==null) {
				holder = new ViewHolder();
				convertView = View.inflate(SubscribeSearchActivity.this,
						R.layout.item_sbuscribe, null);
				holder.iv_icon = (ImageView) convertView
						.findViewById(R.id.iv_sbu_icon);
				holder.tv_name = (TextView) convertView
						.findViewById(R.id.tv_sbu_name);
				holder.tv_number = (TextView) convertView
						.findViewById(R.id.tv_sbu_nub);
				holder.btn_sbu = (Button) convertView
						.findViewById(R.id.btn_sbu);
				convertView.setTag(holder);
			}else{
				holder= (ViewHolder) convertView.getTag();
			}
			SearchBean searchBean=searchData.get(position);
			holder.tv_name.setText(searchBean.theme_name);
			Log.e("TAG", "holder.tv_name");
			holder.tv_number.setText(searchBean.sub_number+0+ "人订阅");
			holder.btn_sbu.setText("+订阅");
			if (!searchBean.image_list.equals("")){
				bitmapUtils.display(holder.iv_icon, searchBean.image_list);
			}else {
				holder.iv_icon.setImageResource(R.drawable.ic_launcher);
			}
			
			return convertView;
		}
		
	}

	

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		Object obj = s;
		Message msg = Message.obtain(handler, 0, obj);
		handler.sendMessage(msg);
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cancel_btn:
			finish();
			break;
		case R.id.fl_bg:
			fl_bg.setVisibility(View.GONE);
			searchData = new ArrayList<SearchBean>();
			getDataFromNet();
			
			break;

		default:
			break;
		}

	}
}
